package com.bharatonjava.swift.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.bharatonjava.swift.dao.mappers.UserRoleExtractor;
import com.bharatonjava.swift.dao.mappers.UserRowMapper;
import com.bharatonjava.swift.domain.User;

@Repository
public class UserDao implements IUserDao {
	private JdbcTemplate jdbcTemplate;

	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public List<User> getAllUsers() {
		String sql = "SELECT U.USERNAME, U.PASSWORD, R.USERNAME, R.ROLENAME FROM USERS U LEFT JOIN USERS_ROLES R ON U.USERNAME = R.USERNAME ORDER BY U.USERNAME";
		List<User> users = this.jdbcTemplate.query(sql, new UserRoleExtractor());
		return users;
	}

	@Override
	public User getUserByUsername(String username) {
		String sql = "SELECT U.USERNAME, R.USERNAME, U.PASSWORD, R.ROLENAME FROM USERS U LEFT JOIN USERS_ROLES R ON U.USERNAME = R.USERNAME WHERE U.USERNAME = ?";
		User user = (User) this.jdbcTemplate.query(sql,
				new Object[] { username }, new UserRoleExtractor());
		return user;
	}

	@Override
	public int addUser(User user) {
		String sql = "INSERT INTO USERS (USERNAME, PASSWORD) VALUES (?,?)";
		int updateCount = this.jdbcTemplate.update(sql,
				new Object[] { user.getUserName(), user.getPassword() });
		return updateCount;
	}

	@Override
	public boolean userExists(User user) {
		String sql = "select true from users where username = ?";
		Boolean exists = this.jdbcTemplate.query(sql,
				new ResultSetExtractor<Boolean>() {

					@Override
					public Boolean extractData(ResultSet rs)
							throws SQLException, DataAccessException {
						Integer value = rs.getInt(1);
						if (value == 1) {
							return true;
						} else {
							return false;
						}
					}
				});
		return exists;
	}

}
